<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>易油互联</title>
  <link rel="stylesheet" href="./yiyou.css">
</head>
<script src="./jquery-3.5.1.min.js"></script>

<body>
  <div class="tree-wrap">
    <div class="tree-type" id="treeType">
    </div>
    <div class="tree-company">
      <div id="treeInnerCompany" class="tree-content"></div>
    </div>
    <div class="tree-department">
      <div id="treeInnerDepartment" class="tree-content"></div>
    </div>
    <div class="tree-selected"></div>
    <p class="clear"></p>
  </div>
  <script src="./data.js"></script>
  <script>
    const typeArr = [
      {
        id: 0,
        name: '内部',
        level: 0,
        parentId: -1,
        type: 'inner'
      },
      {
        id: 1,
        name: '外部',
        level: 0,
        parentId: -1,
        type: 'outter'
      },
      {
        id: 2,
        name: '好友公司',
        level: 1,
        parentId: 1,
        type: 'friend'
      },
      {
        id: 3,
        name: '客商',
        level: 1,
        parentId: 1,
        type: 'customer'
      },
      {
        id: 4,
        name: '供应商',
        level: 1,
        parentId: 1,
        type: 'supply'
      }
    ]

    let typeHtml = ''

    typeArr.map(obj => {
      typeHtml += `<div class="tree-type-list tree-top-${obj.parentId}" data-type="${obj.type}" data-level="${obj.level}" data-pid="${obj.parentId}" data-id="${obj.id}" style="margin-left: ${14 * obj.level}px">`
        + `<input class="tree-type tree-checked-${obj.id}" type="checkbox" onclick="selectChild(this)"/>`
        // + `<input type="checkbox" onclick="checkboxSelected(this)" name="inner-${data.topId ? data.topId : 0}" id="inner-${data.id}">`
        + `<label>${obj.name}</label>`
        + `<p class="clear"></p>`
        + `</div>`
    })

    document.getElementById('treeType').innerHTML = typeHtml

    const innerData = formatCompanyData(dataObj3.innerList)
    const outerData = dataObj2.outerList
    const friendList = formatCompanyData(outerData.friendList)
    let htmlObj = {
      company: '', // 公司
      department: '', // 部门
      friendList: '', // 好友公司
      friendListDepart: '', // 好友公司部门
      customerList: outerData.customerList, // 客商
    }
    createTreeHtml(innerData, 'company')
    createTreeHtml(innerData, 'department')
    createTreeHtml(friendList, 'customer', 'friendList')
    createTreeHtml(friendList, 'department', 'friendListDepart')
    document.getElementById('treeInnerCompany').innerHTML = htmlObj.company
    document.getElementById('treeInnerDepartment').innerHTML = htmlObj.department

    /**
     * 创建树结构数据
     * @param data Array 数据列表
     * @param type String 公司/部门 兼 key
     * @param key String 存放进htmlObj的key
     */
    function createTreeHtml(data, type, key, id = '', checked = false) {
      data.map(obj => {
        if (obj.type === type) {
          htmlObj[key ?? type] += createHtml(obj, '', id, checked)
        }
        if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
          createTreeHtml(obj.childrens, type, key, obj.id, checked)
        }
      })
    }


    function selectChild(t) {
      const level = $(t).parent().attr('data-level')
      const type = $(t).parent().attr('data-type')
      const id = $(t).parent().attr('data-id')
      const pid = $(t).parent().attr('data-pid')
      const isChecked = $(t).prop('checked')

      if (level == 0) {
        const childNodes = $(`.tree-top-${id}`)

        childNodes.each(function () {
          $(this).find('input')[0].checked = isChecked
        })
      } else {
        const childNodes = $(`.tree-top-${pid}`)
        let allChecked = true

        childNodes.each(function () {
          if (!$(this).find('input')[0].checked) {
            allChecked = false
          }
        })

        if (allChecked) {
          $(`.tree-checked-${pid}`)[0].checked = true
        } else {
          $(`.tree-checked-${pid}`)[0].checked = false
        }
      }
    }

    /**
     * createHtml 创建树结构html
     * @param data Object 需要渲染的数据
     * @param html String 生成的html
     */
    function createHtml(data, html = '', pid, checked) {
      const info = JSON.stringify(data).replace(/\"/g, "'")

      html += `<div class="tree-type-list tree-list-${pid}" data-id="${pid}" data-level="${data.realLevel}" style="margin-left: ${14 * (data.realLevel - (data.type === 'company' ? 2 : 3))}px">`
        + `<input type="checkbox" onclick="checkboxSelected(this, &quot;${info}&quot;)" ${checked && 'checked'} name="inner-${data.topId ? data.topId : 0}" id="inner-${data.id}">`
        // + `<input type="checkbox" onclick="checkboxSelected(this)" name="inner-${data.topId ? data.topId : 0}" id="inner-${data.id}">`
        + `<label onclick="showChild(this, ${data.id}, '${data.type}')">${data.name}</label>`
        + `<p class="clear"></p>`
        + `</div>`
      return html
    }

    /**
     * formatCompanyData 格式化公司数据
     * @param data Object 数据对象
     */
    function formatCompanyData(data) {
      Object.keys(data).map(k => {
        let arr = [];
        if (data[k].hasOwnProperty('children') && Object.keys(data[k].children).length > 0) {
          formatCompanyData(data[k].children)
          data[k].childrens = Object.values(data[k].children)
        }
      })
      return Object.values(data)
    }

    /**
     * checkboxSelected 选中复选框
     * @param t 当前元素
     * @param data String|Object 当前 选中/取消 数据
     */
    function checkboxSelected(t, data) {
      let isChecked = t.checked
      let allChecked = []

      // 转换 data 格式
      typeof (data) === 'string' ? data = JSON.parse(data.replace(/\'/g, '"')) : data

      if (data.hasOwnProperty('childrens') && data.childrens.length > 0) {
        allChecked = selectedChildren(t, data)
      }

      allChecked.push(data.id)

      // if (data.type === "company") {
      //   htmlObj.department = ''
      //   createTreeHtml(data.childrens, 'department', 'department', data.id, isChecked)

      //   document.getElementById('treeInnerDepartment').innerHTML = htmlObj.department
      // }


      if (isChecked) {
        selectSuperior(t, data)
      } else {
        unselectSuperior(t, data)
      }
    }

    /**
     * selectedChildren 选中子级
     */
    function selectedChildren(t, data, arr = []) {
      data.childrens.map(obj => {
        arr.push(obj.id)
        const childNode = document.getElementById(`inner-${obj.id}`)

        if (childNode) {
          childNode && (childNode.checked = t.checked)
        }

        if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
          selectedChildren(childNode, obj, arr)
        }
      })
      return arr
    }

    /**
     * createSelectedHtml 创建选中的部门dom
     */
    function createSelectedHtml(name, id) {

    }

    function showChild(v, id, type, data = innerData) {
      if (type == 'company') {
        data.map(obj => {
          if (obj.id == id) {
            const isChecked = v.parentNode.getElementsByTagName('input')[0].checked

            htmlObj.department = ''
            createTreeHtml(obj.childrens, 'department', 'department', id, isChecked)
            document.getElementById('treeInnerDepartment').innerHTML = htmlObj.department
          } else {
            if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
              showChild(v, id, type, obj.childrens)
            }
          }
        })
      }
    }


    /**
     * selectSuperior 递归选中上级
     */
    function selectSuperior(t, data) {
      const pid = $(t).parent().attr('data-id')
      const allBro = $(`.tree-list-${pid}`)
      let allChecked = true

      allBro.each(function () {
        if (!$(this).find('input').prop('checked')) {
          allChecked = false
          return
        }
      })

      if (allChecked) {
        if (pid) {
          const parentNode = $(`#inner-${pid}`)[0]

          $(parentNode).prop('checked', true)
          selectSuperior(parentNode)
        } else {
          $('#inner').prop('checked', true)
        }

      }
    }

    /**
     * selectSuperior 递归取消选中上级
     */
    function unselectSuperior(t, data) {
      const pid = $(t).parent().attr('data-id')

      if (pid) {
        const parentNode = $(`#inner-${pid}`)[0]

        $(parentNode).prop('checked', false)
        unselectSuperior(parentNode)
      } else {
        $('#inner').prop('checked', false)
      }
    }

  </script>
</body>

</html>